import React, { useEffect, useState, Key } from "react";
import { Button, Form, Input, Table, Card, message, Tooltip } from "antd";
import {
  SearchOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
//引入api中请求数据的方法
import {
  getHosSetListRequest,
  deleteHosSetFromIdRequest,
  batchDeleteHosRequest,
} from "@/api/hospital/hospitalSet";

//引入返回record的类型
import type {
  getHosSetListRecordsType,
  getHosSetListItemType,
} from "@/api/hospital/model/hospitalSetType";
import type { searchHosFinishPraType } from "./types";

import style from "./index.module.css";

export default function HospitalSet() {
  //使用编程式路由导航hook
  const navigate = useNavigate();

  //data是表格的数据 每一个对象的中的key和columns中的dataIndex一一对象展示数据
  const [tableData, setTableData] = useState<getHosSetListRecordsType>([]);
  //定义current(当前页码)的state[useState的泛型根据我们传入的参数推论出来了]
  const [current, setCurrent] = useState(1);
  //定义total(总个数)的state
  const [total, setTotal] = useState(0);
  //定义pageSize(每页的数量)的state
  const [pageSize, setPageSize] = useState(3);
  //定义isLoading(table是否加载中)
  const [isLoading, setIsLoading] = useState(false);
  //定义表单事件的值,将其赋值给state
  const [fieldValue, setFieldValue] = useState<searchHosFinishPraType>({});
  //定义一个state,专门用来触发useEffect的执行,重新加载
  const [reRender, setReRender] = useState(true);
  //定义一个控制批量删除按钮的一个状态
  const [isSelect, setIsSelecte] = useState(true);
  //定义一个 保存批量选中的ids的状态
  const [bacthSelectIds, setBatchSelectIds] = useState<Key[]>([]);

  //当组件加载的时候,开始请求分页列表的数据
  //注意:异步函数不能作为useEffect的参数,因为useEffect可能会书写return一个函数起到清理作用,如果是异步函数,则return就是异步的了
  useEffect(() => {
    //在请求开始之前,设置isLoading为true
    setIsLoading(true);
    const getHosSetList = async () => {
      const re = await getHosSetListRequest({
        page: current,
        limit: pageSize,
        ...fieldValue,
      });
      //1.请求到数据后把record设置给state
      setTableData(re.records);
      //2.把得到的结果中 数据的总长度设置给state
      setTotal(re.total);

      //请求完成后要把isLoading修改为false
      setIsLoading(false);
    };
    getHosSetList();
  }, [current, pageSize, fieldValue, reRender]);

  const columns = [
    {
      title: "序号",
      width: 60,
      dataIndex: "index",
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "医院编号",
      dataIndex: "hoscode",
    },
    {
      title: "api基础路径",
      dataIndex: "apiUrl",
      key: "apiUrl",
    },
    {
      title: "签名",
      dataIndex: "signKey",
    },
    {
      title: "联系人姓名",
      dataIndex: "contactsName",
    },
    {
      title: "联系人手机",
      dataIndex: "contactsPhone",
    },
    {
      title: "操作",
      width: 120,
      fixed: "right" as "right",
      dataIndex: "do",
      render(_: any, data: getHosSetListItemType) {
        const { id } = data;
        return (
          <div>
            <Tooltip title="修改医院">
              <Button
                type="primary"
                icon={<EditOutlined />}
                className={style.mr}
                onClick={() => {
                  navigate(`/syt/hospital/updatehosset/${id}`);
                }}
              ></Button>
            </Tooltip>
            <Tooltip title="删除医院">
              <Button
                type="primary"
                danger
                icon={<DeleteOutlined />}
                onClick={deleteHosHandle(id)}
              ></Button>
            </Tooltip>
          </div>
        );
      },
    },
  ];

  //事件回调函数
  //2.点击查询提交表单的事件回调函数
  const searchHosFinishHandle = (fieldValue: searchHosFinishPraType) => {
    setFieldValue(fieldValue);
  };
  //3.添加医院事件回调函数
  const addHosHandle = () => {
    //编程式路由导航跳转
    navigate("/syt/hospital/addhosset");
  };
  //4.删除单个医院的事件回调函数
  const deleteHosHandle = (id: number) => {
    return async () => {
      await deleteHosSetFromIdRequest(id);
      //重新渲染
      setReRender(!reRender);
      message.success("删除医院成功");
    };
  };
  //5.批量删除按钮事件回调函数
  const batchDeleteHandle = async () => {
    await batchDeleteHosRequest(bacthSelectIds);
    message.success("批量删除成功");
    //重新渲染
    setReRender(!reRender);
    //把批量删除按钮恢复
    setIsSelecte(true);
  };

  return (
    <div className={style.outer}>
      <Card>
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 40 }}
          layout="inline"
          onFinish={searchHosFinishHandle}
        >
          <Form.Item name="hosname">
            <Input placeholder="医院名称" />
          </Form.Item>

          <Form.Item name="hoscode">
            <Input placeholder="医院编号" />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="default" htmlType="reset">
              清空
            </Button>
          </Form.Item>
        </Form>
        <div className={style.mt}>
          <Button type="primary" className={style.mr} onClick={addHosHandle}>
            添加
          </Button>
          <Button
            type="primary"
            danger
            disabled={isSelect}
            onClick={batchDeleteHandle}
          >
            批量删除
          </Button>
        </div>
        <Table
          className={style.mt}
          columns={columns}
          dataSource={tableData}
          //滚动条
          scroll={{ x: 1300 }}
          bordered
          //在table中 要求dataSource中有key属性,但是如果真的没有key 则可以使用rowKey属性指定dataSource中的一个属性作为Key
          rowKey="id"
          loading={isLoading}
          rowSelection={{
            onChange(ids: Key[], datas: getHosSetListRecordsType) {
              setIsSelecte(!ids.length);
            },
          }}
          pagination={{
            //页码的配置：当前页码
            current,
            //总数据的数量
            total,
            //每页条数
            pageSize,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [2, 3, 4, 5],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,
            showTotal(total) {
              return `总共有${total}条数据`;
            },
            onChange: (current, pageSize) => {
              setCurrent(current);
              setPageSize(pageSize);
            },
          }}
        />
      </Card>
      ;
    </div>
  );
}
